﻿using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.采购管理.Server;
using ERP_SaaS_WinForm.采购管理; // 确保InspectorSelectionForm类被引用
using ERP_SaaS_WinForm.采购管理.Sup; // 添加AddMaters类的引用
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using ERP_SaaS_WinForm.采购管理.Gong;
using ERP_SaaS_WinForm.销售.Sales;
using CCWin.SkinControl;

namespace ERP_SaaS_WinForm.采购管理
{
    public partial class Quality : CCSkinMain
    {
        private List<GongDto> clientList = new List<GongDto>();
        public GongDto SelectedClient { get; private set; }
        public Quality()
        {
            InitializeComponent();
            // 使用Load事件来确保窗体完全加载后再加载数据
            this.Load += Quality_Load;

            // 为选择按钮绑定点击事件
            this.skinButton3.Click += SkinButton3_Click;
            
            // 为添加按钮绑定点击事件
            this.AddSup.Click += AddSup_Click;
            
            // 为采购列表添加按钮绑定点击事件
            this.butAddMater.Click += butAddMater_Click;

            // 为数据网格绑定双击事件
            if (skinDataGridView1 != null)
            {
                skinDataGridView1.CellDoubleClick += SkinDataGridView1_CellDoubleClick;
                // 添加单元格点击事件来处理详情按钮
                skinDataGridView1.CellClick += SkinDataGridView1_CellClick;
            }
        }


        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private async void Quality_Load(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine("=== Quality窗体开始加载 ===");
                
                // 只设置质检日期的默认值，来料日期保持清空
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                QuaDate.text = today;
                LDate.text = ""; // 来料日期保持清空

                Console.WriteLine("正在加载部门数据...");
                // 先加载部门数据，再加载质检列表
                LoadInspectionDepartments();

                Console.WriteLine("正在生成质检编号...");
                // 自动生成质检编号
                GenerateQualityCode();
                
                Console.WriteLine("正在加载质检列表...");
                LoadQualityList();
                
                Console.WriteLine("正在加载供应商列表...");
                await LoadGongList(null);
                
                Console.WriteLine("正在加载采购列表数据...");
                // 加载采购列表数据
                await LoadPurchasedMaterialsList();
                
                Console.WriteLine("=== Quality窗体加载完成 ===");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Quality窗体加载时发生异常: {ex.Message}");
                MessageBox.Show($"窗体加载失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 加载质检部门数据到下拉框
        /// </summary>

        private async void LoadInspectionDepartments()
        {
            try
            {
                // 显示加载状态
                QuaDepId.Items.Clear();
                QuaDepId.Items.Add("正在加载...");
                QuaDepId.Enabled = false;

                using (HttpClient client = new HttpClient())
                {
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(10);

                    HttpResponseMessage response = await client.GetAsync("http://10.223.8.2:4090/api/Supplier/GetInspectionDepInfo");

                    if (response.IsSuccessStatusCode)
                    {
                        string jsonResult = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"API返回的JSON数据: {jsonResult}");

                        var apiResponse = JsonConvert.DeserializeObject<ApiResponse<List<DepInsop>>>(jsonResult);

                        if (apiResponse != null && apiResponse.Data != null && apiResponse.Code == 200)
                        {
                            QuaDepId.Items.Clear();
                            QuaDepId.DisplayMember = "InsDepName";
                            QuaDepId.ValueMember = "InsDepId";

                            // 添加默认选项
                            QuaDepId.Items.Add(new DepInsop { InsDepId = 0, InsDepName = "请选择部门" });

                            foreach (var dept in apiResponse.Data)
                            {
                                QuaDepId.Items.Add(dept);
                                Console.WriteLine($"添加部门: ID={dept.InsDepId}, Name={dept.InsDepName}");
                            }

                            // 默认选中第一个选项（请选择部门）
                            QuaDepId.SelectedIndex = 0;

                            // 显示加载成功的消息
                            Console.WriteLine($"成功加载 {apiResponse.Data.Count} 个质检部门");
                            MessageBox.Show($"成功加载 {apiResponse.Data.Count} 个质检部门", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            // 部门数据加载成功后，再加载质检列表
                            LoadQualityList();
                        }
                        else
                        {
                            QuaDepId.Items.Clear();
                            QuaDepId.Items.Add("加载失败");
                            MessageBox.Show($"加载质检部门数据失败: {apiResponse?.Msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        QuaDepId.Items.Clear();
                        QuaDepId.Items.Add("HTTP请求失败");
                        MessageBox.Show($"HTTP请求失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                QuaDepId.Items.Clear();
                QuaDepId.Items.Add("加载异常");
                MessageBox.Show($"加载质检部门数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"异常详情: {ex}");
            }
            finally
            {
                QuaDepId.Enabled = true;
            }
        }

        /// <summary>
        /// 加载质检列表数据
        /// </summary>
        private async void LoadQualityList()
        {
            try
            {
                // 显示加载状态
                Console.WriteLine("正在加载质检列表...");
                Console.WriteLine($"skinDataGridView1 控件状态: {(skinDataGridView1 != null ? "找到" : "未找到")}");

                // 检查部门数据是否已加载
                Console.WriteLine($"部门下拉框中的项目数量: {QuaDepId.Items.Count}");
                if (QuaDepId.Items.Count > 0)
                {
                    Console.WriteLine("部门数据已加载，可以正确显示部门名称");
                }
                else
                {
                    Console.WriteLine("警告：部门数据未加载，部门名称可能显示不正确");
                }

                if (skinDataGridView1 == null)
                {
                    MessageBox.Show("数据网格控件未找到，请检查界面设计！", "控件错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                using (HttpClient client = new HttpClient())
                {
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(10);

                    Console.WriteLine("正在调用API: http://10.223.8.2:4090/api/Supplier/GetQulityInfo");
                    HttpResponseMessage response = await client.GetAsync("http://10.223.8.2:4090/api/Supplier/GetQulityInfo");

                    Console.WriteLine($"API响应状态码: {response.StatusCode}");

                    if (response.IsSuccessStatusCode)
                    {
                        string jsonResult = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"质检列表API返回的JSON数据: {jsonResult}");

                        if (string.IsNullOrEmpty(jsonResult))
                        {
                            Console.WriteLine("API返回的JSON数据为空");
                            MessageBox.Show("API返回的数据为空，请检查接口！", "数据错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }

                        var apiResponse = JsonConvert.DeserializeObject<ApiResponse<List<PlanDatas>>>(jsonResult);
                        Console.WriteLine($"API响应解析结果: Code={apiResponse?.Code}, Msg={apiResponse?.Msg}, DataCount={apiResponse?.Data?.Count ?? 0}");

                        if (apiResponse != null && apiResponse.Data != null && apiResponse.Code == 200)
                        {
                            // 清空现有数据
                            skinDataGridView1.Rows.Clear();
                            Console.WriteLine("已清空数据网格");

                            // 不需要添加列，因为Designer中已经定义了列
                            Console.WriteLine($"数据网格现有列数: {skinDataGridView1.Columns.Count}");

                            Console.WriteLine($"开始填充 {apiResponse.Data.Count} 条数据...");

                            // 填充数据 - 使用Designer中定义的列名
                            foreach (var quality in apiResponse.Data)
                            {
                                int rowIndex = skinDataGridView1.Rows.Add();
                                Console.WriteLine($"添加第 {rowIndex + 1} 行数据: {quality.quaCode} - {quality.quaName}");

                                // 使用Designer中定义的列名
                                skinDataGridView1.Rows[rowIndex].Cells["质检编号"].Value = quality.quaCode ?? "";
                                skinDataGridView1.Rows[rowIndex].Cells["Column2"].Value = quality.quaName ?? "";
                                skinDataGridView1.Rows[rowIndex].Cells["Column3"].Value = quality.quaDate.ToString("yyyy-MM-dd");
                                skinDataGridView1.Rows[rowIndex].Cells["Column4"].Value = quality.lDate.ToString("yyyy-MM-dd");
                                skinDataGridView1.Rows[rowIndex].Cells["Column5"].Value = quality.insDepName ?? "";
                                skinDataGridView1.Rows[rowIndex].Cells["Column1"].Value = quality.qualityInspector ?? "";
                                skinDataGridView1.Rows[rowIndex].Cells["Column6"].Value = quality.quaState ? "已合格" : "未合格";

                                // 操作列 - 创建详情按钮
                                Button detailButton = new Button();
                                detailButton.Text = "详情";
                                detailButton.Size = new Size(60, 25);
                                detailButton.BackColor = Color.LightBlue;
                                detailButton.FlatStyle = FlatStyle.Flat;
                                detailButton.Tag = quality; // 存储质检数据
                                detailButton.Click += DetailButton_Click; // 绑定点击事件

                                // 将按钮添加到操作列
                                skinDataGridView1.Rows[rowIndex].Cells["Column7"].Value = "";

                                // 使用DataGridViewButtonCell来显示按钮
                                var buttonCell = new DataGridViewButtonCell();
                                buttonCell.Value = "详情";
                                skinDataGridView1.Rows[rowIndex].Cells["Column7"] = buttonCell;

                                // 存储完整数据到行标签中，方便后续操作
                                skinDataGridView1.Rows[rowIndex].Tag = quality;
                            }

                            Console.WriteLine($"成功加载 {apiResponse.Data.Count} 条质检记录");
                            MessageBox.Show($"成功加载 {apiResponse.Data.Count} 条质检记录", "加载成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            string errorMsg = $"加载质检列表失败: {apiResponse?.Msg ?? "未知错误"}";
                            Console.WriteLine(errorMsg);
                            MessageBox.Show(errorMsg, "加载失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        string errorMsg = $"HTTP请求失败: {response.StatusCode}";
                        Console.WriteLine(errorMsg);
                        MessageBox.Show(errorMsg, "请求失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMsg = $"加载质检列表时发生异常: {ex.Message}";
                Console.WriteLine(errorMsg);
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                MessageBox.Show(errorMsg, "异常错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 加载供应商的供货清单数据
        /// </summary>
     
        private async Task LoadGongList(string UrlName)
        {
            Console.WriteLine("=== LoadGongList 方法开始执行 ===");
            
            try
            {
                Console.WriteLine("开始执行 LoadGongList 方法");
                string buseUrl = "http://10.223.8.2:4090/api/Supplier/GetSupplierList";  // 修改为获取供应商信息的API
                Console.WriteLine($"API地址: {buseUrl}");
                
                using (HttpClient Dclient = new HttpClient())
                {
                    Console.WriteLine("正在发送HTTP请求...");
                    HttpResponseMessage responseMessage = await Dclient.GetAsync(buseUrl);
                    Console.WriteLine($"HTTP响应状态: {responseMessage.StatusCode}");
                    responseMessage.EnsureSuccessStatusCode();
                    
                    string DjsonResponse = await responseMessage.Content.ReadAsStringAsync();
                    Console.WriteLine($"API返回的JSON数据: {DjsonResponse}");
                    
                    GongApiResponse discount = JsonConvert.DeserializeObject<GongApiResponse>(DjsonResponse);
                    
                    if (discount != null && discount.datas != null && discount.datas.Count > 0)
                    {
                        Console.WriteLine($"成功获取到 {discount.datas.Count} 条供应商数据");
                        
                        // 清空表格
                        skinDataGridView2.Rows.Clear();
                        skinDataGridView2.Columns.Clear();
                        
                        // 添加列
                        skinDataGridView2.Columns.Add("供应商编号", "供应商编号");
                        skinDataGridView2.Columns.Add("供应商名称", "供应商名称");
                        skinDataGridView2.Columns.Add("联系人", "联系人");
                        skinDataGridView2.Columns.Add("联系电话", "联系电话");
                        skinDataGridView2.Columns.Add("状态", "状态");
                        
                        // 绑定数据
                        foreach (var supplier in discount.datas)
                        {
                            Console.WriteLine($"正在处理供应商: SupCode='{supplier.SupCode}', SupName='{supplier.SupName}'");
                            
                            int rowIndex = skinDataGridView2.Rows.Add();
                            Console.WriteLine($"添加了第 {rowIndex + 1} 行");
                            
                            // 逐个绑定并验证
                            skinDataGridView2.Rows[rowIndex].Cells[0].Value = supplier.SupCode;
                            Console.WriteLine($"列0绑定完成，值: '{skinDataGridView2.Rows[rowIndex].Cells[0].Value}'");
                            
                            skinDataGridView2.Rows[rowIndex].Cells[1].Value = supplier.SupName;
                            Console.WriteLine($"列1绑定完成，值: '{skinDataGridView2.Rows[rowIndex].Cells[1].Value}'");
                            
                            skinDataGridView2.Rows[rowIndex].Cells[2].Value = supplier.SupPhoneName;
                            Console.WriteLine($"列2绑定完成，值: '{skinDataGridView2.Rows[rowIndex].Cells[2].Value}'");
                            
                            skinDataGridView2.Rows[rowIndex].Cells[3].Value = supplier.SupPhone;
                            Console.WriteLine($"列3绑定完成，值: '{skinDataGridView2.Rows[rowIndex].Cells[3].Value}'");

                            string statusText;
                            if (supplier.SupState == 1)
                            {
                                statusText = "有货";
                            }
                            else if (supplier.SupState == 2)
                            {
                                statusText = "售空";
                            }
                            else
                            {
                                statusText = supplier.SupState.ToString();
                            }
                            skinDataGridView2.Rows[rowIndex].Cells[4].Value = statusText;

                            Console.WriteLine($"第 {rowIndex + 1} 行绑定完成");
                        }
                        
                        Console.WriteLine($"成功绑定 {skinDataGridView2.Rows.Count} 行数据到表格");
                        
                        // 强制刷新表格显示
                        skinDataGridView2.Refresh();
                        Console.WriteLine("表格刷新完成");
                        
                        // 验证最终结果
                        Console.WriteLine($"最终表格状态: {skinDataGridView2.Rows.Count} 行, {skinDataGridView2.Columns.Count} 列");
                        for (int i = 0; i < skinDataGridView2.Rows.Count; i++)
                        {
                            Console.WriteLine($"行 {i + 1}:");
                            for (int j = 0; j < skinDataGridView2.Columns.Count; j++)
                            {
                                var cellValue = skinDataGridView2.Rows[i].Cells[j].Value;
                                Console.WriteLine($"  列{j}: '{cellValue}'");
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("API返回的数据为空或格式不正确");
                        MessageBox.Show("未获取到供应商数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取供应商数据失败: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                MessageBox.Show($"获取供应商数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        /// 根据部门ID获取部门名称
        /// </summary>
        /// <param name="deptId">部门ID</param>
        /// <returns>部门名称</returns>
        private string GetDepartmentNameById(int deptId)
        {
            try
            {
                Console.WriteLine($"正在查找部门ID: {deptId}");
                Console.WriteLine($"部门下拉框中的项目数量: {QuaDepId.Items.Count}");

                // 从下拉框中查找部门名称
                foreach (var item in QuaDepId.Items)
                {
                    if (item is DepInsop dept)
                    {
                        Console.WriteLine($"检查部门: ID={dept.InsDepId}, Name={dept.InsDepName}");
                        if (dept.InsDepId == deptId)
                        {
                            Console.WriteLine($"找到匹配的部门: {dept.InsDepName}");
                            return dept.InsDepName;
                        }
                    }
                    else
                    {
                        Console.WriteLine($"项目类型不是DepInsop: {item?.GetType().Name}");
                    }
                }

                Console.WriteLine($"未找到部门ID {deptId} 对应的部门名称");
                return $"部门ID:{deptId}";
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取部门名称时发生异常: {ex.Message}");
                return $"部门ID:{deptId}";
            }
        }

        /// <summary>
        /// 添加的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AddQur_Click(object sender, EventArgs e)
        {
            try
            {
                // 数据验证
                if (string.IsNullOrWhiteSpace(QuaName.Text.Trim()))
                {
                    MessageBox.Show("请输入质检名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    QuaName.Focus();
                    return;
                }

                if (string.IsNullOrWhiteSpace(QualityInspector.Text.Trim()))
                {
                    MessageBox.Show("请选择质检人员！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 获取选中的部门ID
                int selectedDepId = 0;
                if (QuaDepId.SelectedItem != null)
                {
                    var selectedDept = QuaDepId.SelectedItem as DepInsop;
                    selectedDepId = selectedDept?.InsDepId ?? 0;
                }

                if (selectedDepId == 0)
                {
                    MessageBox.Show("请选择质检部门！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 测试API连接
                Console.WriteLine("正在测试API连接...");
                bool apiConnected = await TestApiConnection();
                if (!apiConnected)
                {
                    Console.WriteLine("API连接测试失败，但继续执行添加操作...");
                }
                else
                {
                    Console.WriteLine("API连接测试通过，继续执行添加操作...");
                }

                // 自动生成质检编号
                string autoGeneratedCode = GenerateQualityCode();

                // 安全解析日期 - 使用ValidateDate方法
                DateTime? quaDateValue = ValidateDate(QuaDate.text, "质检日期");
                if (quaDateValue == null)
                {
                    QuaDate.Focus();
                    return;
                }

                // 来料日期为可选字段，如果为空则使用当前日期
                DateTime lDateValue;
                if (string.IsNullOrWhiteSpace(LDate.text))
                {
                    lDateValue = DateTime.Now; // 如果来料日期为空，使用当前日期
                }
                else
                {
                    DateTime? parsedLDate = ValidateDate(LDate.text, "来料日期");
                    if (parsedLDate == null)
                    {
                        LDate.Focus();
                        return;
                    }
                    lDateValue = parsedLDate.Value;
                }

                // 使用专门的API请求模型
                var apiRequest = new QualityApiRequest
                {
                    quaCode = autoGeneratedCode,
                    quaName = QuaName.Text.Trim(),
                    qualityInspector = QualityInspector.Text.Trim(),
                    quaDepId = selectedDepId,
                    quaDate = quaDateValue.Value, // 使用验证后的DateTime对象
                    lDate = lDateValue,     // 使用验证后的DateTime对象
                    quaRemark = QuaRemark.Text.Trim(),
                    quaState = false
                };

                // 输出调试信息
                Console.WriteLine($"准备发送的数据:");
                Console.WriteLine($"质检编号: {apiRequest.quaCode}");
                Console.WriteLine($"质检名称: {apiRequest.quaName}");
                Console.WriteLine($"质检人员: {apiRequest.qualityInspector}");
                Console.WriteLine($"质检部门ID: {apiRequest.quaDepId}");
                Console.WriteLine($"质检日期: {apiRequest.quaDate}");
                Console.WriteLine($"来料日期: {apiRequest.lDate}");
                Console.WriteLine($"质检备注: {apiRequest.quaRemark}");

                string jsonData = JsonConvert.SerializeObject(apiRequest);
                Console.WriteLine($"序列化后的JSON数据: {jsonData}");

                using (HttpClient client = new HttpClient())
                {
                    // 只设置Accept头，Content-Type头会在StringContent中自动设置
                    client.DefaultRequestHeaders.Add("Accept", "application/json");

                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                    Console.WriteLine($"正在发送请求到: http://10.223.8.2:4090/api/Qulity/AddQuality");
                    Console.WriteLine($"请求内容长度: {jsonData.Length} 字符");

                    HttpResponseMessage response = await client.PostAsync("http://10.223.8.2:4090/api/Qulity/AddQuality", content);

                    Console.WriteLine($"HTTP响应状态码: {response.StatusCode}");
                    Console.WriteLine($"HTTP响应头: {response.Headers}");

                    string responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"API响应内容: {responseContent}");

                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show($"质检信息添加成功！\n质检编号：{autoGeneratedCode}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ClearForm();

                        // 刷新质检列表
                        LoadQualityList();
                    }
                    else
                    {
                        // 尝试解析错误响应
                        try
                        {
                            var errorResponse = JsonConvert.DeserializeObject<dynamic>(responseContent);
                            string errorMessage = errorResponse?.message?.ToString() ?? errorResponse?.msg?.ToString() ?? "未知错误";
                            MessageBox.Show($"质检信息添加失败！\nHTTP状态: {response.StatusCode}\n错误信息: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        catch
                        {
                            MessageBox.Show($"质检信息添加失败！\nHTTP状态: {response.StatusCode}\n响应内容: {responseContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加质检信息时发生异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                MessageBox.Show($"添加质检信息时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 重置的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelQur_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            QuaCode.Text = "";
            QuaName.Text = "";
            QualityInspector.Text = "";
            QuaDepId.SelectedIndex = -1;

            // 只设置质检日期的默认值，来料日期保持清空
            string today = DateTime.Now.ToString("yyyy-MM-dd");
            QuaDate.text = today;
            LDate.text = ""; // 来料日期保持清空

            QuaRemark.Text = "";

            // 自动生成新的质检编号
            GenerateQualityCode();
        }

        /// <summary>
        /// 自动生成质检编号
        /// </summary>
        /// <returns>生成的质检编号</returns>
        private string GenerateQualityCode()
        {
            try
            {
                // 生成格式：QC + 年月日 + 4位序号
                string prefix = "QC";
                string datePart = DateTime.Now.ToString("yyyyMMdd");
                string sequencePart = DateTime.Now.ToString("HHmmss"); // 使用时分秒作为序号

                string qualityCode = $"{prefix}{datePart}{sequencePart}";

                // 将生成的编号显示在编号文本框中
                QuaCode.Text = qualityCode;

                return qualityCode;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"生成质检编号时发生错误: {ex.Message}");
                // 如果生成失败，返回默认编号
                return $"QC{DateTime.Now:yyyyMMddHHmmss}";
            }
        }

        /// <summary>
        /// 测试API连接
        /// </summary>
        private async Task<bool> TestApiConnection()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(10);

                    // 使用已知存在的API端点来测试连接
                    var response = await client.GetAsync("http://10.223.8.2:4090/api/Supplier/GetInspectionDepInfo");

                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("API连接测试成功");
                        return true;
                    }
                    else
                    {
                        Console.WriteLine($"API连接测试失败，状态码: {response.StatusCode}");
                        // 即使测试失败，也允许继续执行，因为可能是测试端点的问题
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"API连接测试异常: {ex.Message}");
                // 如果连接测试失败，仍然允许继续执行，因为可能是网络配置问题
                Console.WriteLine("连接测试失败，但继续执行添加操作...");
                return true;
            }
        }

        /// <summary>
        /// 验证日期格式
        /// </summary>
        /// <param name="dateText">日期字符串</param>
        /// <param name="fieldName">字段名称（用于错误提示）</param>
        /// <returns>解析后的DateTime对象，如果失败则返回null</returns>
        private DateTime? ValidateDate(string dateText, string fieldName)
        {
            if (string.IsNullOrWhiteSpace(dateText))
            {
                MessageBox.Show($"{fieldName}不能为空！", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return null;
            }

            DateTime result;
            if (DateTime.TryParse(dateText, out result))
            {
                return result;
            }
            else
            {
                MessageBox.Show($"{fieldName}格式不正确！\n请使用格式：yyyy-MM-dd\n例如：2025-01-13", "日期格式错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return null;
            }
        }

        /// <summary>
        /// 选择按钮点击事件 - 跳转到Inspection页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SkinButton3_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建并显示Inspection页面，传递Quality窗体的引用
                var inspectionForm = new Inspection(this);
                inspectionForm.StartPosition = FormStartPosition.CenterParent;
                inspectionForm.Show();

                // 可选：隐藏当前Quality页面
                // this.Hide();

                Console.WriteLine("已跳转到Inspection页面");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"跳转到Inspection页面失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"异常详情: {ex}");
            }
        }


        /// <summary>
        /// 刷新质检列表
        /// </summary>
        public void RefreshQualityList()
        {
            LoadQualityList();
          


        }

        /// <summary>
        /// 手动刷新按钮点击事件（如果有刷新按钮的话）
        /// </summary>
        private void RefreshButton_Click(object sender, EventArgs e)
        {
            LoadQualityList();
            


        }

        /// <summary>
        /// <summary>
        /// 数据网格单元格点击事件 - 处理详情按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SkinDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                // 只处理操作列（第8列，索引为7）的点击
                if (e.ColumnIndex == 7 && e.RowIndex >= 0)
                {
                    Console.WriteLine($"操作列被点击，行索引: {e.RowIndex}");

                    // 获取该行的质检数据
                    var qualityData = skinDataGridView1.Rows[e.RowIndex].Tag as PlanDatas;

                    if (qualityData != null)
                    {
                        Console.WriteLine($"详情按钮被点击，质检编号: {qualityData.quaCode}");

                        // 创建并显示Details页面
                        var detailsForm = new Details();
                        detailsForm.StartPosition = FormStartPosition.CenterParent;

                        // 设置质检数据
                        detailsForm.SetQualityData(qualityData);

                        // 显示Details窗体
                        detailsForm.Show();

                        Console.WriteLine("已跳转到Details页面");
                    }
                    else
                    {
                        Console.WriteLine("获取质检数据失败");
                        MessageBox.Show("获取质检数据失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理详情按钮点击时发生异常: {ex.Message}");
                MessageBox.Show($"处理详情按钮点击时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        /// 详情按钮点击事件 - 跳转到Details页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DetailButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender is Button detailButton && detailButton.Tag is PlanDatas qualityData)
                {
                    Console.WriteLine($"详情按钮被点击，质检编号: {qualityData.quaCode}");

                    // 创建并显示Details页面
                    var detailsForm = new Details();
                    detailsForm.StartPosition = FormStartPosition.CenterParent;

                    // 设置质检数据
                    detailsForm.SetQualityData(qualityData);

                    // 显示Details窗体
                    detailsForm.Show();

                    Console.WriteLine("已跳转到Details页面");
                }
                else
                {
                    Console.WriteLine("详情按钮数据获取失败");
                    MessageBox.Show("获取质检数据失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"跳转到Details页面失败：{ex.Message}");
                MessageBox.Show($"跳转到Details页面失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"异常详情: {ex}");
            }
        }
        // <summary>
        /// 数据网格双击事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SkinDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0 && e.RowIndex < skinDataGridView1.Rows.Count)
                {
                    var selectedRow = skinDataGridView1.Rows[e.RowIndex];
                    var qualityData = selectedRow.Tag as PlanDatas;

                    if (qualityData != null)
                    {
                        // 显示详细信息
                        string details = $"质检详细信息：\n" +
                                        $"质检编号：{qualityData.quaCode}\n" +
                                        $"质检名称：{qualityData.quaName}\n" +
                                        $"质检人员：{qualityData.qualityInspector}\n" +
                                        $"质检部门ID：{qualityData.quaDepId}\n" +
                                        $"质检日期：{qualityData.quaDate:yyyy-MM-dd}\n" +
                                        $"来料日期：{qualityData.lDate:yyyy-MM-dd}\n" +
                                        $"质检状态：{(qualityData.quaState ? "已合格" : "未合格")}\n" +
                                        $"质检人员ID：{qualityData.qIId}\n" +
                                        $"质检人员姓名：{qualityData.qIName}";

                        MessageBox.Show(details, "质检详细信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"双击行时发生异常: {ex.Message}");
                MessageBox.Show($"查看详细信息时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }






        /// <summary>
        /// 质检信息API请求模型 - 只包含需要发送给API的字段
        /// </summary>
        public class QualityApiRequest
        {
            /// <summary>
            /// 质检编号
            /// </summary>
            public string quaCode { get; set; }

            /// <summary>
            /// 质检名称
            /// </summary>
            public string quaName { get; set; }

            /// <summary>
            /// 质检人员
            /// </summary>
            public string qualityInspector { get; set; }

            /// <summary>
            /// 质检部门ID
            /// </summary>
            public int quaDepId { get; set; }

            /// <summary>
            /// 质检日期
            /// </summary>
            public DateTime quaDate { get; set; }

            /// <summary>
            /// 来料日期
            /// </summary>
            public DateTime lDate { get; set; }

            /// <summary>
            /// 质检状态
            /// </summary>
            public bool quaState { get; set; }

            /// <summary>
            /// 质检备注
            /// </summary>
            public string quaRemark { get; set; }
            /// <summary>
            /// 质检部门名称
            /// </summary>
            public string insDepName { get; set; }
        }
        /// <summary>
        /// 添加物料的信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddSup_Click(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine("添加按钮被点击，准备跳转到SupAdd窗体");
                
                // 创建并显示SupAdd窗体
                var supAddForm = new SupAdd();
                supAddForm.StartPosition = FormStartPosition.CenterParent;
                supAddForm.Show();
                
                Console.WriteLine("已跳转到SupAdd窗体");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"跳转到SupAdd窗体失败：{ex.Message}");
                MessageBox.Show($"跳转到添加物料页面失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 采购列表添加按钮点击事件 - 跳转到AddMetar页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void butAddMater_Click(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine("采购列表添加按钮被点击，准备跳转到AddMetar页面");
                
                // 直接创建并显示AddMetar窗体，不依赖API调用
                var addMetarForm = new AddMetar();
                addMetarForm.StartPosition = FormStartPosition.CenterParent;
                addMetarForm.Show();
                
                Console.WriteLine("已跳转到AddMetar窗体");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"跳转到AddMetar窗体失败：{ex.Message}");
                MessageBox.Show($"跳转到添加采购页面失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 调用API获取物料信息
        /// </summary>
        /// <returns>物料信息列表</returns>
        private async Task<List<AddMaters>> GetMaterialInfo()
        {
            try
            {
                Console.WriteLine("开始调用物料信息API...");
                string apiUrl = "http://10.223.8.2:4090/api/SupplierPost/GetMaterielInfo";
                Console.WriteLine($"API地址: {apiUrl}");
                
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    Console.WriteLine("正在发送HTTP请求...");
                    HttpResponseMessage response = await client.GetAsync(apiUrl);
                    Console.WriteLine($"HTTP响应状态: {response.StatusCode}");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        string jsonResponse = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"API返回的JSON数据: {jsonResponse}");
                        
                        if (string.IsNullOrEmpty(jsonResponse))
                        {
                            Console.WriteLine("API返回的JSON数据为空");
                            return new List<AddMaters>();
                        }
                        
                        // 尝试解析API响应
                        try
                        {
                            // 假设API返回的是直接的物料列表
                            var materialList = JsonConvert.DeserializeObject<List<AddMaters>>(jsonResponse);
                            
                            if (materialList != null)
                            {
                                Console.WriteLine($"成功解析 {materialList.Count} 条物料信息");
                                return materialList;
                            }
                            else
                            {
                                Console.WriteLine("JSON解析结果为空");
                                return new List<AddMaters>();
                            }
                        }
                        catch (JsonException jsonEx)
                        {
                            Console.WriteLine($"JSON解析失败: {jsonEx.Message}");
                            
                            // 尝试解析为包装格式的响应
                            try
                            {
                                var apiResponse = JsonConvert.DeserializeObject<ApiResponse<List<AddMaters>>>(jsonResponse);
                                if (apiResponse?.Data != null)
                                {
                                    Console.WriteLine($"成功解析包装格式的响应，获取到 {apiResponse.Data.Count} 条物料信息");
                                    return apiResponse.Data;
                                }
                            }
                            catch (Exception ex2)
                            {
                                Console.WriteLine($"包装格式解析也失败: {ex2.Message}");
                            }
                            
                            return new List<AddMaters>();
                        }
                    }
                    else
                    {
                        Console.WriteLine($"HTTP请求失败: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"错误响应内容: {errorContent}");
                        return new List<AddMaters>();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取物料信息时发生异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return new List<AddMaters>();
            }
        }
        /// <summary>
        /// 加载采购列表数据
        /// </summary>
        private async Task LoadPurchasedMaterialsList()
        {
            try
            {
                Console.WriteLine("开始加载采购列表数据...");

                if (skinDataGridView3 == null)
                {
                    Console.WriteLine("采购列表数据网格控件未找到");
                    return;
                }

                // 检查DataGridView的列是否存在
                Console.WriteLine($"DataGridView列数: {skinDataGridView3.Columns.Count}");
                foreach (DataGridViewColumn col in skinDataGridView3.Columns)
                {
                    Console.WriteLine($"列名: {col.Name}, 标题: {col.HeaderText}, 索引: {col.Index}");
                }

                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);

                    string apiUrl = "http://10.223.8.2:4090/api/Supplier/GetPurchasedMaterials";
                    Console.WriteLine($"采购列表API地址: {apiUrl}");

                    Console.WriteLine("正在发送HTTP请求...");
                    HttpResponseMessage response = await client.GetAsync(apiUrl);
                    Console.WriteLine($"HTTP响应状态: {response.StatusCode}");

                    if (response.IsSuccessStatusCode)
                    {
                        string jsonResponse = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"采购列表API返回的JSON数据: {jsonResponse}");

                        if (string.IsNullOrEmpty(jsonResponse))
                        {
                            Console.WriteLine("API返回的JSON数据为空");
                            return;
                        }

                        // 尝试解析API响应
                        try
                        {
                            // 假设API返回的是直接的物料列表
                            var materialsList = JsonConvert.DeserializeObject<List<MaterDto>>(jsonResponse);

                            if (materialsList != null && materialsList.Count > 0)
                            {
                                Console.WriteLine($"成功解析 {materialsList.Count} 条采购物料信息");

                                // 清空现有数据
                                skinDataGridView3.Rows.Clear();
                                Console.WriteLine("已清空DataGridView数据");

                                // 填充数据到DataGridView
                                foreach (var material in materialsList)
                                {
                                    Console.WriteLine($"正在处理物料: {material.MaterialCode} - {material.MaterialName}");

                                    int rowIndex = skinDataGridView3.Rows.Add();
                                    Console.WriteLine($"添加了第 {rowIndex + 1} 行");

                                    // 使用列索引绑定数据，避免列名问题
                                    try
                                    {
                                        // 物料编号 - 第0列
                                        if (skinDataGridView3.Columns.Count > 0)
                                        {
                                            skinDataGridView3.Rows[rowIndex].Cells[0].Value = material.MaterialCode ?? "";
                                            Console.WriteLine($"列0绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[0].Value}'");
                                        }

                                        // 物料名称 - 第1列
                                        if (skinDataGridView3.Columns.Count > 1)
                                        {
                                            skinDataGridView3.Rows[rowIndex].Cells[1].Value = material.MaterialName ?? "";
                                            Console.WriteLine($"列1绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[1].Value}'");
                                        }

                                        // 单位 - 第2列
                                        if (skinDataGridView3.Columns.Count > 2)
                                        {
                                            skinDataGridView3.Rows[rowIndex].Cells[2].Value = material.Unit ?? "";
                                            Console.WriteLine($"列2绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[2].Value}'");
                                        }

                                        // 规格型号 - 第3列
                                        if (skinDataGridView3.Columns.Count > 3)
                                        {
                                            skinDataGridView3.Rows[rowIndex].Cells[3].Value = material.Specification ?? "";
                                            Console.WriteLine($"列3绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[3].Value}'");
                                        }

                                        // 采购数量 - 第4列
                                        if (skinDataGridView3.Columns.Count > 4)
                                        {
                                            skinDataGridView3.Rows[rowIndex].Cells[4].Value = material.PurchaseQuantity.ToString();
                                            Console.WriteLine($"列4绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[4].Value}'");
                                        }

                                        // 操作列 - 第5列
                                        if (skinDataGridView3.Columns.Count > 5)
                                        {
                                            skinDataGridView3.Rows[rowIndex].Cells[5].Value = "编辑";
                                            Console.WriteLine($"列5绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[5].Value}'");
                                        }

                                        // 存储完整数据到行标签中，方便后续操作
                                        skinDataGridView3.Rows[rowIndex].Tag = material;

                                        Console.WriteLine($"第 {rowIndex + 1} 行绑定完成");
                                    }
                                    catch (Exception cellEx)
                                    {
                                        Console.WriteLine($"绑定第 {rowIndex + 1} 行数据时发生异常: {cellEx.Message}");
                                    }
                                }

                                // 强制刷新表格显示
                                skinDataGridView3.Refresh();
                                Console.WriteLine("表格刷新完成");

                                // 验证最终结果
                                Console.WriteLine($"最终表格状态: {skinDataGridView3.Rows.Count} 行, {skinDataGridView3.Columns.Count} 列");
                                for (int i = 0; i < skinDataGridView3.Rows.Count; i++)
                                {
                                    Console.WriteLine($"行 {i + 1}:");
                                    for (int j = 0; j < skinDataGridView3.Columns.Count; j++)
                                    {
                                        var cellValue = skinDataGridView3.Rows[i].Cells[j].Value;
                                        Console.WriteLine($"  列{j}: '{cellValue}'");
                                    }
                                }

                                Console.WriteLine($"成功加载 {materialsList.Count} 条采购物料记录");
                                MessageBox.Show($"成功加载 {materialsList.Count} 条采购物料记录", "加载成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                Console.WriteLine("API返回的物料列表为空");
                                MessageBox.Show("未获取到采购物料数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                        catch (JsonException jsonEx)
                        {
                            Console.WriteLine($"JSON解析失败: {jsonEx.Message}");

                            // 尝试解析为包装格式的响应
                            try
                            {
                                var apiResponse = JsonConvert.DeserializeObject<ApiResponse<List<MaterDto>>>(jsonResponse);
                                if (apiResponse?.Data != null && apiResponse.Data.Count > 0)
                                {
                                    Console.WriteLine($"成功解析包装格式的响应，获取到 {apiResponse.Data.Count} 条采购物料信息");

                                    // 清空现有数据
                                    skinDataGridView3.Rows.Clear();
                                    Console.WriteLine("已清空DataGridView数据");

                                    // 填充数据到DataGridView
                                    foreach (var material in apiResponse.Data)
                                    {
                                        Console.WriteLine($"正在处理物料: {material.MaterialCode} - {material.MaterialName}");

                                        int rowIndex = skinDataGridView3.Rows.Add();
                                        Console.WriteLine($"添加了第 {rowIndex + 1} 行");

                                        // 使用列索引绑定数据
                                        try
                                        {
                                            // 物料编号 - 第0列
                                            if (skinDataGridView3.Columns.Count > 0)
                                            {
                                                skinDataGridView3.Rows[rowIndex].Cells[0].Value = material.MaterialCode ?? "";
                                                Console.WriteLine($"列0绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[0].Value}'");
                                            }

                                            // 物料名称 - 第1列
                                            if (skinDataGridView3.Columns.Count > 1)
                                            {
                                                skinDataGridView3.Rows[rowIndex].Cells[1].Value = material.MaterialName ?? "";
                                                Console.WriteLine($"列1绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[1].Value}'");
                                            }

                                            // 单位 - 第2列
                                            if (skinDataGridView3.Columns.Count > 2)
                                            {
                                                skinDataGridView3.Rows[rowIndex].Cells[2].Value = material.Unit ?? "";
                                                Console.WriteLine($"列2绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[2].Value}'");
                                            }

                                            // 规格型号 - 第3列
                                            if (skinDataGridView3.Columns.Count > 3)
                                            {
                                                skinDataGridView3.Rows[rowIndex].Cells[3].Value = material.Specification ?? "";
                                                Console.WriteLine($"列3绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[3].Value}'");
                                            }

                                            // 采购数量 - 第4列
                                            if (skinDataGridView3.Columns.Count > 4)
                                            {
                                                skinDataGridView3.Rows[rowIndex].Cells[4].Value = material.PurchaseQuantity.ToString();
                                                Console.WriteLine($"列4绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[4].Value}'");
                                            }

                                            // 操作列 - 第5列
                                            if (skinDataGridView3.Columns.Count > 5)
                                            {
                                                skinDataGridView3.Rows[rowIndex].Cells[5].Value = "编辑";
                                                Console.WriteLine($"列5绑定完成，值: '{skinDataGridView3.Rows[rowIndex].Cells[5].Value}'");
                                            }

                                            // 存储完整数据到行标签中，方便后续操作
                                            skinDataGridView3.Rows[rowIndex].Tag = material;

                                            Console.WriteLine($"第 {rowIndex + 1} 行绑定完成");
                                        }
                                        catch (Exception cellEx)
                                        {
                                            Console.WriteLine($"绑定第 {rowIndex + 1} 行数据时发生异常: {cellEx.Message}");
                                        }
                                    }

                                    // 强制刷新表格显示
                                    skinDataGridView3.Refresh();
                                    Console.WriteLine("表格刷新完成");

                                    // 验证最终结果
                                    Console.WriteLine($"最终表格状态: {skinDataGridView3.Rows.Count} 行, {skinDataGridView3.Columns.Count} 列");
                                    for (int i = 0; i < skinDataGridView3.Rows.Count; i++)
                                    {
                                        Console.WriteLine($"行 {i + 1}:");
                                        for (int j = 0; j < skinDataGridView3.Columns.Count; j++)
                                        {
                                            var cellValue = skinDataGridView3.Rows[i].Cells[j].Value;
                                            Console.WriteLine($"  列{j}: '{cellValue}'");
                                        }
                                    }

                                    Console.WriteLine($"成功加载 {apiResponse.Data.Count} 条采购物料记录");
                                    MessageBox.Show($"成功加载 {apiResponse.Data.Count} 条采购物料记录", "加载成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                                else
                                {
                                    Console.WriteLine("包装格式API返回的物料列表为空");
                                    MessageBox.Show("未获取到采购物料数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                            }
                            catch (Exception ex2)
                            {
                                Console.WriteLine($"包装格式解析也失败: {ex2.Message}");
                                MessageBox.Show("解析采购物料数据失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"HTTP请求失败: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"错误响应内容: {errorContent}");
                        MessageBox.Show($"获取采购物料数据失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载采购列表数据时发生异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                MessageBox.Show($"加载采购列表数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


    }


    /// <summary>
    /// API响应模型 - 根据实际API响应结构调整
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ApiResponse<T>
    {
        public string Msg { get; set; }
        public int Code { get; set; }
        public T Data { get; set; }
        public object Datas { get; set; }
    }
    /// <summary>
    /// 加载采购列表数据
    /// </summary>
    
}

